import argparse
import os
import subprocess
import sys
import traceback


class ExampleRunner:
    """示例运行器"""

    def __init__(self):
        self.examples = {
            "basic": {
                "file": "basic_usage.py",
                "description": "基本使用示例 - 展示如何初始化和使用 Qwen 模型"
            },
            "chain": {
                "file": "chain_examples.py",
                "description": "链式调用示例 - 展示代码审查和文档问答功能"
            },
            "advanced": {
                "file": "advanced_features.py",
                "description": "高级特性示例 - 展示记忆功能和 Agent 功能"
            }
        }

    def list_examples(self):
        """列出所有可用的示例"""
        try:
            print("\n可用的示例:")
            print("=" * 50)
            for key, info in self.examples.items():
                print(f"\n{key}:")
                print(f"  文件: {info['file']}")
                print(f"  描述: {info['description']}")
                # 检查文件是否存在
                if os.path.exists(info['file']):
                    print(f"  状态: ✓ 文件存在")
                else:
                    print(f"  状态: ✗ 文件不存在")
            print("\n" + "=" * 50)
        except Exception as e:
            print(f"列出示例时出错: {str(e)}")
            traceback.print_exc()

    def run_example(self, example_key: str, timeout: int = 300) -> bool:
        """运行指定的示例"""
        try:
            if example_key not in self.examples:
                print(f"错误: 未知的示例 '{example_key}'")
                return False

            example = self.examples[example_key]
            file_path = example["file"]

            if not os.path.exists(file_path):
                print(f"错误: 找不到文件 '{file_path}'")
                return False

            print(f"\n{'=' * 50}")
            print(f"运行示例: {example_key}")
            print(f"文件: {file_path}")
            print(f"描述: {example['description']}")
            print(f"{'=' * 50}\n")

            # 设置环境变量
            env = os.environ.copy()
            env["PYTHONIOENCODING"] = "utf-8"

            # 使用 subprocess.Popen 启动进程
            process = subprocess.Popen(
                [sys.executable, file_path],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding='utf-8',
                errors='replace',
                env=env
            )

            # 实时读取输出
            while True:
                output = process.stdout.readline()
                if output == '' and process.poll() is not None:
                    break
                if output:
                    print(output.strip())

            # 检查是否有错误
            stderr_output = process.stderr.read()
            if stderr_output:
                print("\n错误输出:")
                print(stderr_output)

            return process.returncode == 0

        except subprocess.TimeoutExpired:
            print(f"\n错误: 示例运行超时（{timeout}秒）")
            return False
        except Exception as e:
            print(f"\n错误: {str(e)}")
            traceback.print_exc()
            return False


def check_environment():
    """检查运行环境"""
    print("\n检查运行环境...")
    print("=" * 50)

    # 检查 Python 版本
    print(f"Python 版本: {sys.version}")

    # 检查当前目录
    print(f"当前目录: {os.getcwd()}")

    # 检查文件权限
    print("\n检查文件权限:")
    for file in ["basic_usage.py", "chain_examples.py", "advanced_features.py"]:
        if os.path.exists(file):
            print(f"✓ {file} 存在")
            try:
                with open(file, 'r', encoding='utf-8') as f:
                    f.read(1)
                print(f"  - 可读")
            except Exception as e:
                print(f"  - 不可读: {str(e)}")
        else:
            print(f"✗ {file} 不存在")

    print("=" * 50)


def main():
    """主函数"""
    try:
        parser = argparse.ArgumentParser(description="运行 LangChain 示例")
        parser.add_argument(
            "example",
            nargs="?",
            help="要运行的示例名称 (basic/chain/advanced)"
        )
        parser.add_argument(
            "--list",
            "-l",
            action="store_true",
            help="列出所有可用的示例"
        )
        parser.add_argument(
            "--timeout",
            "-t",
            type=int,
            default=300,
            help="运行超时时间（秒）"
        )
        parser.add_argument(
            "--check",
            "-c",
            action="store_true",
            help="检查运行环境"
        )

        args = parser.parse_args()
        runner = ExampleRunner()

        # 检查环境
        if args.check:
            check_environment()
            return

        if args.list or not args.example:
            runner.list_examples()
            if not args.example:
                return

        success = runner.run_example(args.example, args.timeout)
        sys.exit(0 if success else 1)

    except Exception as e:
        print(f"程序运行出错: {str(e)}")
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
